package interfaz;

import org.uqbar.commons.model.UserException;
import org.uqbar.lacar.ui.model.Adapter;

import tablero.Coordenada;

public class CoodenadaAdapter implements Adapter<Coordenada, String> {

	@Override
	public Class<Coordenada> getModelType() {
		return Coordenada.class;
	}

	@Override
	public Class<String> getViewType() {
		return String.class;
	}

	@Override
	public String modelToView(Coordenada coord) {
			return String.valueOf(coord.getX());
	}

	@Override
	public Coordenada viewToModel(String cx) {
		Coordenada c = new Coordenada();
		String[] split = cx.split(",");
		if(split.length == 2){
			c.setX(validateInteger(split[0]));
			c.setY(validateInteger(split[1]));				
		}else{
			if(!split[0].equals("")){
				throw new UserException("Coordenada mal formada. utilize la notación x,y");
			}
		}
	
		return c;
	}
	
	private int validateInteger(String string) {
		try {
			return Integer.parseInt(string);	
		} catch (NumberFormatException e) {
			throw new UserException("Ambas componentes deben ser números");
		}
	}

	

}
